package com.sondon.mayi.activity;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sondon.mayi.configs.URLConfigs;
import com.sondon.mayi.entity.LoginEntity;
import com.sondon.mayi.fruit.R;
import com.sondon.mayi.ui.MyMultipleTopBar;
import com.sondon.mayi.ui.TopBarClickListener;
import com.sondon.mayi.util.AsyncHttpUtil;
import com.sondon.mayi.util.CheckUtil;
import com.sondon.mayi.util.DecriptUtil;
import com.sondon.mayi.util.GsonUtil;
import com.sondon.mayi.util.LogUtil;
import com.sondon.mayi.util.NetWorkUtil;
import com.sondon.mayi.util.StringUtil;
import com.sondon.mayi.util.ToastUtils;

/**
 * @Project : Fruit
 * @Package : com.sondon.mayi.activity
 * @Class : ForgetPasswdActvitity.java
 * @Company 广州讯动网络科技有限公司
 * @Author : 蔡文锋
 * @DateTime：2015-6-12 上午10:58:49
 * @Blog：http://blog.csdn.net/caiwenfeng_for_23
 * @Description : {忘记密码,验证手机验证码}
 */
@EActivity(R.layout.forgetpasswd)
public class ForgetPasswdActvitity extends BaseActivity {
	@ViewById
	MyMultipleTopBar topBar;
	@ViewById
	Button next_butt;
	@ViewById
	EditText mobile;
	@ViewById
	EditText checkcode;
	@ViewById
	TextView send_auth;
	
	
	// 重新发送短信验证码
	private final static int TAKETIME = 0x11;
	// 填写从短信SDK应用后台注册得到的APPKEY
	private static String APPKEY = "7feda74f80a0";// 463db7238681 27fe7909f8e8
	// 填写从短信SDK应用后台注册得到的APPSECRET
	private static String APPSECRET = "2d722dcb6befe3ab4ef4ec62c1a2f107";//
	
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case TAKETIME:
				Integer m = (Integer) msg.obj;
				if (m > 0) {
					send_auth.setClickable(false);
					send_auth.setText("再次发送(" + m + ")");
				} else {
					send_auth.setText("再次发送");
					send_auth.setClickable(true);
				}
				break;
			case SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE:
				ToastUtils.show(getApplicationContext(), "提交验证码成功");
				//忘记密码登录
				String phone = mobile.getText().toString().trim();
				RequestParams params=new RequestParams();
				params.put("username",phone);
	            params.put("str", ""+System.currentTimeMillis());
	            params.put("token", DecriptUtil.SHA1(DecriptUtil.MD5(phone)+System.currentTimeMillis()));
				AsyncHttpUtil.post(URLConfigs.NoPasswdLogin, params, loginResponseHandler);
				break;
			case SMSSDK.EVENT_GET_VERIFICATION_CODE:
				ToastUtils.show(getApplicationContext(), "验证码已经发送");
				new Thread(new Runnable() {

					@Override
					public void run() {
						int m = 60;
						while (m > -1) {
							Message msg = new Message();
							msg.what = TAKETIME;
							msg.obj = m;
							handler.sendMessage(msg);
							try {
								Thread.sleep(1000);
								m = m - 1;
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}).start();

				break;
			default:
				break;
			}

		}

	};
	@AfterViews
	public void initView() {
		topBar.setTopBarClickListener(new TopBarClickListener() {
			@Override
			public void rightBtnClick() {
			}
			@Override
			public void leftBtnClick() {
				onBackPressed();
			}
		});
		
		initShareSDK();
	}

	//点击事件
		@Click({ R.id.next_butt, R.id.send_auth})
		public void OnClick(View v) {
			String phone = mobile.getText().toString().trim();
			String code = checkcode.getText().toString().trim();

			// 判断是否为空
			if (StringUtil.isEmpty(phone)) {
				ToastUtils.show(context, R.string.input_mobile);
				return;
			}

			switch (v.getId()) {
			case R.id.next_butt:
				// 判断是否为空
				if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(code)) {
					ToastUtils.show(context, "手机号或验证码不能为空!");
					return;
				}

				// 判断是否有网络
				if (!NetWorkUtil.isNetworkAvailable(context)) {
					ToastUtils.show(context, R.string.network_unavailable);
					return;
				}
				myprefs.phone().put(phone);
				SMSSDK.submitVerificationCode("86", phone, code);
				break;
			case R.id.send_auth:
				if (CheckUtil.isMobile(phone)) {
					SMSSDK.getVerificationCode("86", phone);
				} else {
					ToastUtils.show(context, "请输入合法的手机号码");
				}
				break;
			default:
				break;
			}
		}
	
	
	// 初始化shareSDK
	public void initShareSDK() {
		SMSSDK.initSDK(this, APPKEY, APPSECRET);

		// event事件
		EventHandler eh = new EventHandler() {

			@Override
			public void afterEvent(int event, int result, Object data) {

				if (result == SMSSDK.RESULT_COMPLETE) {
					Message msg = new Message();
					
					if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
						//提交验证码成功
						msg.what = SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE;
						handler.sendMessage(msg);
					} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
						//发送验证码成功
						msg.what = SMSSDK.EVENT_GET_VERIFICATION_CODE;
						handler.sendMessage(msg);
					}
				} else {
					((Throwable) data).printStackTrace();
				}
			}

		};
		// 注册回调事件
		SMSSDK.registerEventHandler(eh);
	}
	
	
	
	//请求响应监听
	TextHttpResponseHandler loginResponseHandler =new TextHttpResponseHandler() {
		
		@Override
		public void onSuccess(int statusCode, Header[] arg1, String json) {
			if(statusCode==200){
				LogUtil.e(TAG, "ForgetPasswdLoginActivity  json :"+json);
				LoginEntity loginEntity=GsonUtil.GetFromJson(json, LoginEntity.class);
				if(loginEntity.isStatus()){
					//记录is_login
					myprefs.is_login().put(true);
					//记录Ukey
					myprefs.Ukey().put(loginEntity.getUkey());
					//跳转
//					Bundle bundle=new Bundle();
//					bundle.putInt("position", 0);
//					openActivity(MainTabActivity_.class,bundle);
					myprefs.position().put(0);
					openActivity(MainTabActivity_.class);
					
					finish();
				}else{
					ToastUtils.show(context,loginEntity.getMsg());
				}
			}
		}
		
		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
			ToastUtils.show(context, R.string.login_fail);
		}
	};
}
